<template>
  <div>
    <n-card title="局部重绘" bordered  >
      <template #header-extra>
        <n-button size="small" type="primary" style="margin-left: 5px;" @click="canvasUndo">
          撤销
        </n-button>
        <n-button size="small" type="primary" style="margin-left: 5px;" @click="canvasRedo">
          回撤
        </n-button>
        <n-button size="small" type="warning" style="margin-left: 5px;" @click="resetImg"> 清除</n-button>
        <n-divider vertical></n-divider>
        <n-button  size="small" type="warning" @click="props.closeAction">关闭</n-button>
      </template>
      <n-space justify="center">
        <div class="canvas-wrapper">
          <canvas
              ref="canvasRef"
              :width="canvasWidth"
              :height="canvasHeight"
              @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing" ></canvas>
          <img
              ref="img2img_imgRef"
              :style="{
                      width: canvasWidth + 'px',
                      height: canvasHeight + 'px'
                      }"
              v-if="props.storyBoard.imgFileId"
              :src="fileFunction.getViewFilePathByUserFileId(props.storyBoard.imgFileId)"
              alt=""
              @load="handleImgLoad"/>
          <img
            ref="img2img_imgRef"
            :style="{
                      width: canvasWidth + 'px',
                      height: canvasHeight + 'px'
                      }"
            v-else
            :src="fileFunction.getViewFilePathByUserFileId(props.storyBoard.imageUrl)"
            alt=""
            @load="handleImgLoad"/>
        </div>
      </n-space>
      <n-form-item label="重绘提示词:">
        <n-input v-model:value="prompt"></n-input>
        <n-button style="margin-left: 5px;" type="primary" @click="inpaint">开始</n-button>
      </n-form-item>
    </n-card>
  </div>
</template>

<style scoped>

</style>
<script setup lang="ts">
// 设置canvas宽高
import {ref} from "vue";
import fileFunction from "@/libs/globalFunction/file";
import {storyBoardController} from "@/api/controller/story/storyBoard.api";


const props = defineProps({

  closeAction:{
    type: Function,
    required: true
  },
  storyBoard:{
    type: Object,
    required: true
  },
  inPaintAction:{
    type: Function,
    required: true
  }
})

const canvasRef = ref(null)
const ctx = ref(null)
const drawing = ref(false)
const canvasHistory = ref([])
const drawStep = ref(-1)
const canvasWidth = ref(600)
const canvasHeight = ref(600)
const imageWidth = ref(0)
const imageHeight = ref(0)
const prompt = ref('')

const handleImgLoad =  (e: any) => {
  const image = e.target;
  let image_new = new Image()
  image_new.src = image.src
  imageWidth.value = image_new.width
  imageHeight.value = image_new.height
  image_new.onload = function () {
    ctx.value = canvasRef.value.getContext('2d')
    // 计算图片宽高比例
    let imgRatio = image_new.width / image_new.height
    if (image_new.width > 600
        || image_new.height > 600) {
      // 计算缩放后的宽高
      if (imgRatio > 1) {
        canvasWidth.value = 600
        canvasHeight.value = image_new.height / (image_new.width / 600)
      } else {
        // 图片比较宽
        canvasWidth.value = image_new.width / (image_new.height / 600)
        canvasHeight.value = 600
      }
    } else {
      canvasWidth.value = image_new.width
      canvasHeight.value = image_new.height
    }
  }
}



const startDrawing = (e: any) => {
  if (!ctx.value) return;
  ctx.value.strokeStyle = 'white'
  ctx.value.fillStyle = 'white'
  drawing.value = true
  if (drawing.value ) {
    ctx.value.beginPath()
    ctx.value.moveTo(e.clientX - canvasRef.value.getBoundingClientRect().left, e.clientY - canvasRef.value.getBoundingClientRect().top)
  }
}


const draw = (e: any) => {
  if (!drawing.value ) return;
  drawCircle(e)
}


const stopDrawing = () => {
  drawing.value = false
  ctx.value.closePath()
  drawStep.value = drawStep.value + 1
  if (drawStep.value < canvasHistory.value.length) {
    canvasHistory.value.length = drawStep.value; // 截断数组
  }
  canvasHistory.value.push(canvasRef.value.toDataURL())
}



const canvasUndo = () => {
  if (drawStep.value > 0) {
    drawStep.value = drawStep.value - 1
    let canvasPic = new Image();
    canvasPic.src = canvasHistory.value[drawStep.value]
    canvasPic.addEventListener('load', () => {
      ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
      console.log(canvasPic)
      ctx.value.drawImage(canvasPic, 0, 0)
    });
  } else {
    ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
  }
}


const canvasRedo = () => {
  if (drawStep.value < canvasHistory.value.length - 1) {
    drawStep.value = drawStep.value + 1;
    let canvasPic = new Image();
    canvasPic.src = canvasHistory.value[drawStep.value]
    canvasPic.addEventListener('load', () => {
      ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
      ctx.value.drawImage(canvasPic, 0, 0);
    });
  }
}



const resetImg = () => {
  ctx.value.clearRect(0, 0, canvasWidth.value, canvasHeight.value)
  canvasHistory.value = []
}





const drawCircle = (e: any) => {
  ctx.value.beginPath();
  ctx.value.fillStyle = '#2196f3';
  ctx.value.strokeStyle = '#2196f3';
  ctx.value.globalAlpha = 0.1
  ctx.value.arc(e.clientX - canvasRef.value.getBoundingClientRect().left, e.clientY - canvasRef.value.getBoundingClientRect().top, 10, 0, Math.PI * 2);
  ctx.value.stroke()
  ctx.value.fill()

  ctx.value.beginPath();
  ctx.value.fillStyle = '#2196f3';
  ctx.value.strokeStyle = '#2196f3';
  ctx.value.globalAlpha = 1
  ctx.value.arc(e.clientX - canvasRef.value.getBoundingClientRect().left, e.clientY - canvasRef.value.getBoundingClientRect().top, 10, 0, Math.PI * 2);
  ctx.value.stroke()
  ctx.value.fill()
  ctx.value.closePath()
}


const getBase64Mask = async () => {
  const imageData = ctx.value.getImageData(0, 0, canvasWidth.value, canvasHeight.value)
  const imageDataContent = imageData.data;
  // 修改图像数据中的像素颜色
  for (let i = 0; i < imageDataContent.length; i += 4) {
    // 判断透明度是否小于阈值
    if (imageDataContent[i + 3] < 128) {
      // 将透明部分设置为黑色
      imageDataContent[i] = 0;
      imageDataContent[i + 1] = 0;
      imageDataContent[i + 2] = 0;
      imageDataContent[i + 3] = 255;
    } else {
      // 将线条部分设置为白色
      imageDataContent[i] = 255;
      imageDataContent[i + 1] = 255;
      imageDataContent[i + 2] = 255;
      imageDataContent[i + 3] = 255;
    }
  }
  console.log(imageData)
  // 将修改后的图像数据导出为图片格式
  const exportCanvas = document.createElement('canvas');
  console.log(exportCanvas)
  exportCanvas.width = canvasWidth.value
  exportCanvas.height = canvasHeight.value
  const exportCtx = exportCanvas.getContext('2d');
  exportCtx.putImageData(imageData, 0, 0);
  // mask放大到和原图一致
  return new Promise((resolve, reject) => {
    // scaleImage(exportCanvas.toDataURL(), sdImg2ImgPrompt.width, sdImg2ImgPrompt.height)
    const image = new Image()
    image.src = exportCanvas.toDataURL()
    image.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = imageWidth.value
      canvas.height = imageHeight.value
      const ctx_canvas = canvas.getContext('2d')
      ctx_canvas.drawImage(image, 0, 0, imageWidth.value, imageHeight.value);
      resolve(canvas.toDataURL())
    }
  })
}

const inpaint = async () =>{
  const response = await getBase64Mask()
  props.inPaintAction(response,prompt.value,props.storyBoard.id)
}
</script>
